

// 基础颜色渲染着色器程序
const colorShaderProgram = [
    `
        attribute vec3 position;
        attribute vec4 color;
        varying vec4 vColor;
        uniform mat4 modelMatrix;
        uniform mat4 viewMatrix;
        uniform mat4 projectionMatrix;
        
        void main() {
            gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
            vColor = color;
        }
    `,
    `
        precision mediump float;
        varying vec4 vColor;
        
        void main() {
            gl_FragColor = vColor;
        }
    `
];

// 光照渲染着色器程序
const lightShaderProgram = [
    `
        attribute vec3 position;
        attribute vec3 normal;
        uniform mat4 modelMatrix;
        uniform mat4 viewMatrix;
        uniform mat4 projectionMatrix;
        uniform vec3 lightPosition;
        
        varying vec3 vNormal;
        varying vec3 vPosition;
        
        void main() {
            gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
            vNormal = mat3(transpose(inverse(modelMatrix))) * normal;
            vPosition = vec3(modelMatrix * vec4(position, 1.0));
        }
    `,
    `
        precision mediump float;
        varying vec3 vNormal;
        varying vec3 vPosition;
        
        void main() {
            vec3 lightDir = normalize(lightPosition - vPosition);
            float diff = max(dot(vNormal, lightDir), 0.0);
            vec3 color = vec3(1.0, 0.0, 0.0);
            gl_FragColor = vec4(diff * color, 1.0);
        }
    `
];

class Mat4 {
    matrix = new Float32Array(16);
    constructor(
        m00 = 1, m01 = 0, m02 = 0, m03 = 0,
        m10 = 0, m11 = 1, m12 = 0, m13 = 0,
        m20 = 0, m21 = 0, m22 = 1, m23 = 0,
        m30 = 0, m31 = 0, m32 = 0, m33 = 1,
    ) {
        let m = this.matrix;
        if (m00 instanceof Float32Array) {
            m = m00;
        } else {
            m[0] = m00; m[1] = m01; m[2] = m02; m[3] = m03;
            m[4] = m10; m[5] = m11; m[6] = m12; m[7] = m13;
            m[8] = m20; m[9] = m21; m[10] = m22; m[11] = m23;
            m[12] = m30; m[13] = m31; m[14] = m32; m[15] = m33;
        }

    }
    static mul(out, a, b) {
        let outm = out.matrix, am = a.matrix, bm = b.matrix;
        outm[0] = am[0] * bm[0] + am[1] * bm[4] + am[2] * bm[8] + am[3] * bm[12];
        outm[1] = am[0] * bm[1] + am[1] * bm[5] + am[2] * bm[9] + am[3] * bm[13];
        outm[2] = am[0] * bm[2] + am[1] * bm[6] + am[2] * bm[10] + am[3] * bm[14];
        outm[3] = am[0] * bm[3] + am[1] * bm[7] + am[2] * bm[11] + am[3] * bm[15];
        return out;
    }

    static mulScaler(out, num) {
        let m = out.matrix;
        m[0] *= num; m[1] *= num; m[2] *= num; m[3] *= num;
        m[4] *= num; m[5] *= num; m[6] *= num; m[7] *= num;
        m[8] *= num; m[9] *= num; m[10] *= num; m[11] *= num;
        m[12] *= num; m[13] *= num; m[14] *= num; m[15] *= num;
        return this;
    }
    static copy(out, a) {
        let m = out.matrix, am = a.matrix;
        m[0] = am[0];
        m[1] = am[1];
        m[2] = am[2];
        m[3] = am[3];
        m[4] = am[4];
        m[5] = am[5];
        m[6] = am[6];
        m[7] = am[7];
        m[8] = am[8];
        m[9] = am[9];
        m[10] = am[10];
        m[11] = am[11];
        m[12] = am[12];
        m[13] = am[13];
        m[14] = am[14];
        m[15] = am[15];
        return out;
    }
    mul(a) {
        return Mat4.mul(this, this, a);
    }
    mulScalar(num) {
        return Mat4.mulScaler(this, num);
    }
}
class Trs {
    static toMat4(out, trs) {
        let mat = out.matrix;
        let x = trs[3], y = trs[4], z = trs[5], w = trs[6];
        let sx = trs[7], sy = trs[8], sz = trs[9];
        let xx = x * x;
        let xy = x * y;
        let xz = x * z;
        let yy = y * y;
        let yz = y * z;
        let zz = z * z;
        let wx = w * x;
        let wy = w * y;
        let wz = w * z;
        mat[0] = (1 - 2 * (yy + zz)) * sx;
        mat[1] = (2 * (xy - wz)) * sx;
        mat[2] = (2 * (xz + wy)) * sx;
        mat[3] = 0;
        mat[4] = (2 * (xy + wz)) * sy;
        mat[5] = (1 - 2 * (xx + zz)) * sy;
        mat[6] = (2 * (yz - wx)) * sy;
        mat[7] = 0;
        mat[8] = (2 * (xz - wy)) * sz;
        mat[9] = (2 * (yz + wx)) * sz;
        mat[10] = (1 - 2 * (xx + yy)) * sz;
        mat[11] = 0;


        mat[12] = trs[0];
        mat[13] = trs[1];
        mat[14] = trs[2];
        mat[15] = 1;

        return out;
    }
}
class Vec3 {
    x = 0;
    y = 0;
    z = 0;
    constructor(x = 0, y = 0, z = 0) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
    add(v) {
        this.x += v.x;
        this.y += v.y;
        this.z += v.z;
        return this;
    }
    sub(v) {
        this.x -= v.x;
        this.y -= v.y;
        this.z -= v.z;
        return this;
    }
    mul(s) {
        this.x *= s;
        this.y *= s;
        this.z *= s;
        return this;
    }
    length() {
        return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
    }
    lengthSquared() {
        return this.x * this.x + this.y * this.y + this.z * this.z;
    }
    toArray() {
        return [this.x, this.y, this.z];
    }
    static fromArray(arr) {
        return new Vec3(arr[0], arr[1], arr[2]);
    }
}
class BoundingSphere {
    center = null;
    radius = 0;

    constructor(center, radius) {
        this.center = center;
        this.radius = radius;
    }

    isInView(camera) {
        const distanceSquared = this.center.sub(camera.position).lengthSquared();
        const cameraFarPlane = 1000.0; // 假设相机的远剪裁面
        const radiusSquared = this.radius * this.radius;

        return distanceSquared < (camera.position.z + cameraFarPlane) * (camera.position.z + cameraFarPlane) + radiusSquared;
    }
}
class Renderer {
    static _instance = null;
    static get instance() {
        if (!this._instance) {
            this._instance = new Renderer();
        }
        return this._instance;
    }

    canvas = null;
    constructor() {
        this.canvas = document.getElementById("webglCanvas");
        const gl = this.canvas.getContext("webgl");

        if (!gl) {
            alert("您的浏览器不支持 WebGL");
        }
        this.gl = gl;
        // this.setCamera(camera);
    }
    setCamera(camera) {
        this.camera = camera;
    }
    // 创建和编译着色器函数
    createShader(type, source) {
        let gl = this.gl;
        const shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            console.error("Shader compile error:", gl.getShaderInfoLog(shader));
        }
        return shader;
    }

    // 创建程序并链接函数
    createProgram([vertexShaderSource, fragmentShaderSource]) {
        let gl = this.gl;
        const program = gl.createProgram();
        const vertexShader = this.createShader(gl.VERTEX_SHADER, vertexShaderSource);
        const fragmentShader = this.createShader(gl.FRAGMENT_SHADER, fragmentShaderSource);
        gl.attachShader(program, vertexShader);
        gl.attachShader(program, fragmentShader);
        gl.linkProgram(program);
        if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
            console.error("Program link error:", gl.getProgramInfoLog(program));
        }
        gl.useProgram(program);
        return program;
    }

    render(models) {
        let gl = this.gl;
        gl.clearColor(0.0, 0.0, 0.0, 1.0); // 设置背景颜色
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // 清空颜色和深度缓冲区

        let camera = this.camera;
        camera.updateViewMatrix();
        models.forEach(model => {
            if (model instanceof Model && model.loaded /* && model.boundingSphere.isInView(camera)*/) {
                model.updateModelMatrix();

                // 使用模型的着色器程序
                gl.useProgram(model.program);


                // 绑定顶点数据和索引数据
                gl.bindBuffer(gl.ARRAY_BUFFER, model.buffers.vertexBuffer);
                const positionAttributeLocation = gl.getAttribLocation(model.program, "position");
                gl.enableVertexAttribArray(positionAttributeLocation);
                gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 7 * Float32Array.BYTES_PER_ELEMENT, 0);

                const colorAttributeLocation = gl.getAttribLocation(model.program, "color");
                gl.enableVertexAttribArray(colorAttributeLocation);
                gl.vertexAttribPointer(colorAttributeLocation, 4, gl.FLOAT, false, 7 * Float32Array.BYTES_PER_ELEMENT, 3 * Float32Array.BYTES_PER_ELEMENT);
                // if (model.program === lightShaderProgram) {
                //     gl.bindBuffer(gl.ARRAY_BUFFER, model.buffers.normalBuffer);
                //     const normalAttributeLocation = gl.getAttribLocation(model.program, "normal");
                //     gl.enableVertexAttribArray(normalAttributeLocation);
                //     gl.vertexAttribPointer(normalAttributeLocation, 3, gl.FLOAT, false, 0, 0);
                // }

                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, model.buffers.indexBuffer);

                // 设置模型矩阵
                const modelMatrixLocation = gl.getUniformLocation(model.program, "modelMatrix");
                gl.uniformMatrix4fv(modelMatrixLocation, false, model.modelMatrix.matrix);

                // 设置视图矩阵
                const viewMatrixLocation = gl.getUniformLocation(model.program, "viewMatrix");
                gl.uniformMatrix4fv(viewMatrixLocation, false, camera.viewMatrix.matrix);

                // 设置投影矩阵
                const projectionMatrixLocation = gl.getUniformLocation(model.program, "projectionMatrix");
                gl.uniformMatrix4fv(projectionMatrixLocation, false, camera.setPerspectiveProjectionMatrix());
                // 绘制模型
                gl.drawElements(gl.TRIANGLES, model.buffers.indexCount, gl.UNSIGNED_SHORT, 0);
            }
        });
    }
}
class Camera {
    position = null;
    rotation = null;
    viewMatrix = null;
    constructor() {
        this.position = new Vec3(0, 0, -10);
        this.rotation = new Quaternion();
        this.viewMatrix = new Mat4();
        this.updateViewMatrix()
    }
    render() {
        // TODO: 实现相机渲染
        this.updateViewMatrix()
    }
    updateViewMatrix() {
        // viewMatrix[12] = -this.position.x;
        // viewMatrix[13] = -this.position.y;
        // viewMatrix[14] = this.position.z;
        // console.log(cameraX,cameraY,cameraZ)
        // viewMatrix = multiplyMatrix(viewMatrix,newViewMatrix)
        // viewMatrix = new Float32Array(newViewMatrix)
        // console.log('updateViewMatrix', viewMatrix)
        // this.viewMatrix = { matrix: this.rotation.toRotationMatrix() };
        // this.viewMatrix.matrix[14] = this.position.z;
        let trs = [
            -this.position.x,
            -this.position.y,
            this.position.z,
            this.rotation.x,
            this.rotation.y,
            this.rotation.z,
            this.rotation.w,
            1,
            1,
            1,
        ]
        Trs.toMat4(this.viewMatrix, trs)
        // console.log('camera updateViewMatrix', this.viewMatrix)
    }
    // 设置投影矩阵（透视投影）
    setPerspectiveProjectionMatrix() {
        let canvas = Renderer.instance.canvas;
        const fovy = Math.PI / 3; // 45度
        const tanHalfFovy = Math.tan(fovy / 2);
        const aspect = canvas.width / canvas.height;
        const near = 0.51;
        const far = 1000.0;

        const projectionMatrix = new Float32Array(16);
        projectionMatrix[0] = 1.0 / (aspect * tanHalfFovy);
        projectionMatrix[5] = 1.0 / tanHalfFovy;
        projectionMatrix[10] = -(far + near) / (far - near);
        projectionMatrix[11] = -1.0;
        projectionMatrix[14] = -(2.0 * far * near) / (far - near);
        projectionMatrix[15] = 0.0;
        return projectionMatrix;
    }
    // 设置投影矩阵（正交投影）
    setOrthographicProjectionMatrix() {
        let canvas = Renderer.instance.canvas;
        const left = -canvas.width / 2;
        const right = canvas.width / 2;
        const bottom = -canvas.height / 2;
        const top = canvas.height / 2;
        const near = 0.1;
        const far = 100000.0;
        const projectionMatrix = new Float32Array(16);
        projectionMatrix[0] = 2.0 / (right - left);
        projectionMatrix[5] = 2.0 / (top - bottom);
        projectionMatrix[10] = -2.0 / (far - near);
        projectionMatrix[12] = -(right + left) / (right - left);
        projectionMatrix[13] = -(top + bottom) / (top - bottom);
        projectionMatrix[14] = -(far + near) / (far - near);
        projectionMatrix[15] = 1.0;
        return projectionMatrix;
    }
}
class Model {
    name = "NewModel"
    position = null;
    rotation = null;
    scale = null;
    boundingSphere = null; // 添加包围球属性
    buffers = null;
    program = null;
    modelMatrix = null;
    loaded = false;
    constructor(name) {
        this.name = name;
        this.position = new Vec3(0, 0, 0);
        this.rotation = new Quaternion();
        this.scale = new Vec3(1, 1, 1);
        this.modelMatrix = new Mat4();
        this.updateBoundingSphere();
    }
    setScale(xOrScale, y, z) {
        // TODO: 实现设置模型缩放
        if (xOrScale instanceof Vec3) {
            this.scale = xOrScale;
        }
        else {
            this.scale.x = xOrScale;
            this.scale.y = y;
            this.scale.z = z;
        }
        this.updateBoundingSphere();
    }
    setPosition(xOrPos, y, z) {
        // TODO: 实现设置模型位置
        if (xOrPos instanceof Vec3) {
            this.position = xOrPos;
        } else {
            this.position.x = xOrPos;
            this.position.y = y;
            this.position.z = z;
        }
        this.updateBoundingSphere();
    }
    setProgram(program) {
        this.program = program;
    }
    static parseObj(content) {
        const lines = content.split("\n");
        const vertices = [];
        const normals = [];
        const textureCoords = [];
        const faces = [];

        lines.forEach((line) => {
            const values = line.split(" ");
            const type = values[0];

            switch (type) {
                case "v": // 顶点
                    vertices.push(
                        parseFloat(values[1]),
                        parseFloat(values[2]),
                        parseFloat(values[3])
                    );
                    break;

                case "vt": // 纹理坐标
                    textureCoords.push(
                        parseFloat(values[1]),
                        parseFloat(values[2])
                    );
                    break;

                case "vn": // 法线
                    normals.push(
                        parseFloat(values[1]),
                        parseFloat(values[2]),
                        parseFloat(values[3])
                    );
                    break;

                case "f": // 面
                    const face = values.slice(1).map((vertex) => {
                        const indices = vertex
                            .split("/")
                            .map((index) => parseInt(index));
                        return indices;
                    });
                    faces.push(face);
                    break;

                default:
                    break;
            }
        });

        // console.log('Vertices:', vertices);
        // console.log('Normals:', normals);
        // console.log('Texture Coords:', textureCoords);
        // console.log('Faces:', faces);

        return { vertices, normals, textureCoords, faces };
    }
    insertOnes(arr) {
        // 检查数组长度是否是3的倍数
        if (arr.length % 3 !== 0) {
            throw new Error("数组长度必须是3的倍数");
        }

        // 创建一个新数组来存储结果
        let result = [];

        // 遍历原始数组
        for (let i = 0; i < arr.length; i++) {
            // 将当前元素添加到结果数组中
            result.push(arr[i]);

            // 每三个元素后插入四个1
            if ((i + 1) % 3 === 0) {
                result.push(Math.random(), Math.random(), Math.random(), 1);
            }
        }

        return result;
    }
    async loadBuffers(gl, url) {

        let response = await fetch(url);
        let text = await response.text()
        // console.log("response", text);
        let obj = Model.parseObj(text);
        let cubeVertices = [];
        let cubeIndices = [];
        // let obj = await loadModelData("../models/test.obj");
        console.log("obj", obj);
        for (let i = 0; i < obj.faces.length; i++) {
            const face = obj.faces[i];
            for (let offset = 0; offset < face.length - 2; offset++) {
                cubeIndices.push(
                    face[0][0] - 1,
                    face[1 + offset][0] - 1,
                    face[2 + offset][0] - 1
                );
            }
        }
        cubeVertices = obj.vertices;
        cubeVertices = this.insertOnes(cubeVertices);
        console.log(cubeIndices, cubeVertices);
        this.buffers = this.createBuffers(gl, cubeVertices, obj.normals, cubeIndices);
        this.loaded = true;
    }
    updateBoundingSphere() {
        // 假设模型的半径为最大顶点到中心的距离
        const maxDistance = Math.max(this.scale.x, this.scale.y, this.scale.z);
        this.boundingSphere = new BoundingSphere(this.position, maxDistance);
    }
    createBuffers(gl, vertices, normals, indices) {
        const vertexBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

        const normalBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(normals), gl.STATIC_DRAW);

        const indexBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);

        return { vertexBuffer, normalBuffer, indexBuffer, indexCount: indices.length };
    }
    updateModelMatrix() {
        let trs = [
            this.position.x,
            this.position.y,
            this.position.z,
            this.rotation.x,
            this.rotation.y,
            this.rotation.z,
            this.rotation.w,
            this.scale.x,
            this.scale.y,
            this.scale.z

        ]
        Trs.toMat4(this.modelMatrix, trs);
    }
}
class Quaternion {
    constructor(w = 1, x = 0, y = 0, z = 0) {
        this.w = w;
        this.x = x;
        this.y = y;
        this.z = z;
    }

    // 四元数乘法
    multiply(other) {
        const w = this.w * other.w - this.x * other.x - this.y * other.y - this.z * other.z;
        const x = this.w * other.x + this.x * other.w + this.y * other.z - this.z * other.y;
        const y = this.w * other.y - this.x * other.z + this.y * other.w + this.z * other.x;
        const z = this.w * other.z + this.x * other.y - this.y * other.x + this.z * other.w;
        return new Quaternion(w, x, y, z);
    }

    // 从轴角生成四元数
    static fromAxisAngle(axis, angle) {
        const halfAngle = angle / 2;
        const s = Math.sin(halfAngle);
        const w = Math.cos(halfAngle);
        const x = axis[0] * s;
        const y = axis[1] * s;
        const z = axis[2] * s;
        return new Quaternion(w, x, y, z);
    }

    // 四元数转旋转矩阵
    toRotationMatrix() {
        const w = this.w;
        const x = this.x;
        const y = this.y;
        const z = this.z;

        const ww = w * w;
        const wx = w * x;
        const wy = w * y;
        const wz = w * z;
        const xx = x * x;
        const xy = x * y;
        const xz = x * z;
        const yy = y * y;
        const yz = y * z;
        const zz = z * z;

        return [
            ww + xx - yy - zz, 2 * (xy - wz), 2 * (xz + wy), 0,
            2 * (xy + wz), ww - xx + yy - zz, 2 * (yz - wx), 0,
            2 * (xz - wy), 2 * (yz + wx), ww - xx - yy + zz, 0,
            0, 0, 0, 1
        ];
    }
}
(async function () {
    isDragging = false;
    // 触摸事件处理
    let lastTouchX = 0;
    let lastTouchY = 0;
    let rotationX = 0;
    let rotationY = 0;

    window.addEventListener("touchstart", (e) => {
        lastTouchX = e.touches[0].clientX;
        lastTouchY = e.touches[0].clientY;
    });

    window.addEventListener("touchmove", (e) => {
        if (e.touches.length === 1) {
            const touch = e.touches[0];
            const deltaX = touch.clientX - lastTouchX;
            const deltaY = touch.clientY - lastTouchY;

            rotationX += deltaY * 0.01; // 控制旋转速度
            rotationY += deltaX * 0.01;

            lastTouchX = touch.clientX;
            lastTouchY = touch.clientY;
        }
    });

    window.addEventListener("contextmenu", (e) => {
        e.preventDefault();
    });
    // 鼠标事件处理
    window.addEventListener("mousedown", (e) => {
        e.preventDefault();
        isDragging = true;
        lastX = e.clientX;
        lastY = e.clientY;
    });

    window.addEventListener("mousemove", (e) => {
        if (isDragging) {
            const newX = e.clientX;
            const newY = e.clientY;
            const deltaX = -newX + lastX;
            const deltaY = -newY + lastY;
            // const deltaX = touch.clientX - lastTouchX;
            // const deltaY = touch.clientY - lastTouchY;

            // 计算旋转角度
            const rotationY = deltaX * 0.01; // 水平滑动对应Y轴旋转
            const rotationX = deltaY * 0.01; // 垂直滑动对应X轴旋转

            // 创建绕Y轴的四元数
            let yRotationQuat = Quaternion.fromAxisAngle([0, 1, 0], rotationY);

            // 创建绕X轴的四元数
            let xRotationQuat = Quaternion.fromAxisAngle([1, 0, 0], rotationX);


            // 更新模型矩阵
            // updateModelMatrix();

            if (e.buttons === 1) {
                console.log('左键')
                // 组合旋转
                model1.rotation = model1.rotation.multiply(yRotationQuat); // 先绕Y轴旋转
                model1.rotation = model1.rotation.multiply(xRotationQuat); // 再绕X轴旋转
            } else if (e.buttons === 2) {
                console.log('右键')

                let camera = Renderer.instance.camera;
                // 组合旋转
                camera.rotation = camera.rotation.multiply(yRotationQuat); // 先绕Y轴旋转
                // camera.rotation = camera.rotation.multiply(xRotationQuat); // 再绕X轴旋转
                // Renderer.instance.camera.updateViewMatrix();

            }
            // 更新触摸点位置
            lastX = newX;
            lastY = newY;
        }
    });

    window.addEventListener("mouseup", () => {
        isDragging = false;
    });

    window.addEventListener("keydown", (e) => {
        console.log(e)
        let code = e.code;
        let move_dist = 0.05;
        if (code === "KeyW") {
            cameraZ += move_dist;
        }
        else if (code === "KeyS") {
            cameraZ -= move_dist;
        }
        else if (code === "KeyA") {
            cameraX -= move_dist;
        }
        else if (code === "KeyD") {
            cameraX += move_dist;
        }
        else if (code === "KeyQ") {
            cameraY -= move_dist;
        }
        else if (code === "KeyE") {
            cameraY += move_dist;
        }
    });
    // 初始化场景
    let models = [];
    window.models = models;
    let camera = new Camera();
    window.camera = camera;
    let renderer = Renderer.instance;
    let gl = renderer.gl;
    Renderer.instance.setCamera(camera);
    let model1 = new Model('test1');
    model1.setPosition(1, 0, 0);
    model1.setScale(1, 1, 1);
    model1.loadBuffers(renderer.gl, '../models/test.obj');
    model1.setProgram(renderer.createProgram(colorShaderProgram));
    let model2 = new Model('test2');
    model2.setPosition(-2, 0, 0);
    model2.setScale(1, 1, 1);
    model2.loadBuffers(renderer.gl, '../models/test.obj');
    model2.setProgram(renderer.createProgram(colorShaderProgram));

    models.push(model1, model2);
    // 绘制函数
    function draw() {

        renderer.render(models); // 调用渲染器渲染模型
        requestAnimationFrame(draw);
    }

    // 启用深度测试
    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
    // 开始绘制
    // applyRotationX(0);
    // applyRotationY(0);
    draw();
})();